<template>
  <el-dialog
    title="导入供应商报价"
    top="5vh"
    :visible.sync="dialogValue"
    width="1000px"
    :close-on-click-modal="false"
    append-to-body
  >
    <div class="import-quote">
      <div class="supplier-info">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="供应商名称">{{ supplierInfo?.supplier?.name }}</el-descriptions-item>
          <el-descriptions-item label="联系人">{{ supplierInfo?.supplier?.contact_person }}</el-descriptions-item>
          <el-descriptions-item label="比价项目">{{ biddingInfo?.title }}</el-descriptions-item>
          <el-descriptions-item label="比价月份">{{ biddingInfo?.month }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <div class="import-steps">
        <el-steps :active="currentStep" finish-status="success" simple>
          <el-step title="上传Excel文件" icon="el-icon-upload"></el-step>
          <el-step title="预览数据" icon="el-icon-view"></el-step>
          <el-step title="确认导入" icon="el-icon-check"></el-step>
        </el-steps>
      </div>

      <!-- 步骤1：上传Excel文件 -->
      <div v-if="currentStep === 0" class="step-content">
        <h4>请上传供应商报价Excel文件</h4>
        <div class="upload-area">
          <el-upload
            class="upload-demo"
            drag
            :auto-upload="false"
            :on-change="handleFileChange"
            :before-upload="beforeUpload"
            accept=".xlsx,.xls"
            :show-file-list="false"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传xlsx/xls文件，且不超过10MB</div>
          </el-upload>
        </div>

        <div class="template-download">
          <h5>Excel模板格式说明：</h5>
          <p>请按照以下列顺序填写数据：</p>
          <ul>
            <li><strong>菜品分类</strong>：如"蔬菜类"、"肉类"等</li>
            <li><strong>菜品名称</strong>：具体的菜品名称</li>
            <li><strong>单位</strong>：如"斤"、"个"、"份"等</li>
            <li><strong>报价</strong>：供应商报价（数字格式）</li>
          </ul>
          <el-button type="text" @click="downloadTemplate">下载Excel模板</el-button>
        </div>
      </div>

      <!-- 步骤2：预览数据 -->
      <div v-if="currentStep === 1" class="step-content">
        <h4>预览导入数据</h4>
        <div class="preview-info">
          <el-alert
            :title="getPreviewTitle()"
            :type="getPreviewType()"
            :closable="false"
            show-icon
          >
            <div slot="description">
              <p>官方参考价格表共 <strong>{{ dishList.length }}</strong> 个菜品</p>
              <p>有效报价：<strong>{{ validDataCount }}</strong> 个</p>
              <p v-if="getMissingCount() > 0">缺失报价：<strong style="color: #E6A23C;">{{ getMissingCount() }}</strong> 个</p>
              <p v-if="getExtraCount() > 0">多余菜品：<strong style="color: #F56C6C;">{{ getExtraCount() }}</strong> 个（无法提交）</p>
            </div>
          </el-alert>
        </div>
        <el-table
          size="large"
          stripe
          border
          :data="previewData"
          row-key="rowNumber"
          max-height="400px"
        >
          <el-table-column prop="rowNumber" label="行号" width="80">
            <template slot-scope="scope">
              <span v-if="scope.row.rowNumber">{{ scope.row.rowNumber }}</span>
              <span v-else style="color: #999;">-</span>
            </template>
          </el-table-column>
          <el-table-column prop="category" label="菜品分类" width="150">
            <template slot-scope="scope">
              <span v-if="scope.row.isExtra" style="color: #F56C6C;">{{ scope.row.category }}</span>
              <span v-else>{{ scope.row.category }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="菜品名称" min-width="200">
            <template slot-scope="scope">
              <span v-if="scope.row.isExtra" style="color: #F56C6C;">{{ scope.row.name }}</span>
              <span v-else>{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="unit" label="单位" width="100">
            <template slot-scope="scope">
              <span v-if="scope.row.isExtra" style="color: #F56C6C;">{{ scope.row.unit }}</span>
              <span v-else>{{ scope.row.unit }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="quoted_price" label="报价" width="120">
            <template slot-scope="scope">
              <span v-if="scope.row.status === 'valid'" style="color: #E6A23C; font-weight: bold;">¥{{ scope.row.quoted_price }}</span>
              <span v-else-if="scope.row.isExtra" style="color: #F56C6C;">{{ scope.row.quoted_price }}</span>
              <span v-else style="color: #f56c6c;">{{ scope.row.quoted_price }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status === 'valid'" type="success">有效</el-tag>
              <el-tag v-else-if="scope.row.isExtra" type="danger">多余</el-tag>
              <el-tag v-else type="warning">无效</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="error" label="错误信息" min-width="200">
            <template slot-scope="scope">
              <span v-if="scope.row.error" style="color: #f56c6c;">{{ scope.row.error }}</span>
              <span v-else style="color: #67c23a;">✓</span>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 步骤3：确认导入 -->
      <div v-if="currentStep === 2" class="step-content">
        <h4>确认导入</h4>
        <div class="confirm-info">
          <el-alert
            :title="getConfirmTitle()"
            :type="getConfirmType()"
            :closable="false"
            show-icon
          >
            <div slot="description">
              <p>供应商：<strong>{{ supplierInfo?.supplier?.name }}</strong></p>
              <p>官方参考价格表共 <strong>{{ dishList.length }}</strong> 个菜品</p>
              <p>将导入 <strong>{{ validDataCount }}</strong> 条有效报价</p>
              <p v-if="getMissingCount() > 0" style="color: #E6A23C;">缺失报价：<strong>{{ getMissingCount() }}</strong> 个菜品</p>
              <p v-if="getExtraCount() > 0" style="color: #F56C6C;">多余菜品：<strong>{{ getExtraCount() }}</strong> 个（将被忽略）</p>
              <p style="margin-top: 10px;">导入后将覆盖该供应商的现有报价数据</p>
            </div>
          </el-alert>
        </div>
      </div>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button @click="prevStep" v-if="currentStep > 0">上一步</el-button>
      <el-button @click="dialogValue = false">取消</el-button>
      <el-button
        type="primary"
        @click="nextStep"
        v-if="currentStep < 2"
        :disabled="currentStep === 1 && getExtraCount() > 0"
      >
        下一步
      </el-button>
      <el-button
        type="success"
        :loading="importLoading"
        @click="confirmImport"
        v-if="currentStep === 2"
        :disabled="getExtraCount() > 0"
      >
        确认导入
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { http } from '@/api';
import * as XLSX from 'xlsx';

export default {
  name: 'ImportQuote',
  data() {
    return {
      dialogValue: false,
      currentStep: 0,
      supplierInfo: null,
      biddingInfo: null,
      uploadedFile: null,
      previewData: [],
      validDataCount: 0,
      dishList: [], // 官方参考价格表中的菜品列表
      importLoading: false
    };
  },
  methods: {
    open(supplierInfo, biddingInfo) {
      this.supplierInfo = supplierInfo;
      this.biddingInfo = biddingInfo;
      this.dialogValue = true;
      this.currentStep = 0;
      this.uploadedFile = null;
      this.previewData = [];
      this.loadDishList();
    },

    loadDishList() {
      // 加载官方参考价格表中的菜品列表
      http.dish.list({ monthly_bidding_id: this.biddingInfo.id }).then(res => {
        this.dishList = res.data || [];
      }).catch(() => {
        this.$message.error('获取官方参考价格表失败');
      });
    },

    nextStep() {
      if (this.currentStep === 0) {
        if (!this.uploadedFile) {
          this.$message.warning('请先上传Excel文件');
          return;
        }
      }
      if (this.currentStep === 1) {
        if (this.validDataCount === 0) {
          this.$message.warning('没有有效的数据可以导入');
          return;
        }
      }
      this.currentStep++;
    },

    prevStep() {
      this.currentStep--;
    },

    beforeUpload(file) {
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                      file.type === 'application/vnd.ms-excel';
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isExcel) {
        this.$message.error('只能上传Excel文件!');
        return false;
      }
      if (!isLt10M) {
        this.$message.error('文件大小不能超过10MB!');
        return false;
      }
      return true;
    },

    handleFileChange(file) {
      if (!file) return;

      const reader = new FileReader();
      reader.onload = (e) => {
        try {
          this.uploadedFile = e.target.result;
          this.parseExcelData();
        } catch (error) {
          console.error('文件读取失败:', error);
          this.$message.error('文件读取失败');
        }
      };
      reader.onerror = () => {
        this.$message.error('文件读取失败');
      };
      reader.readAsArrayBuffer(file.raw);
    },

    async parseExcelData() {
      try {
        // 从上传的文件数据中解析Excel
        const workbook = XLSX.read(this.uploadedFile, { type: 'array' });
        const sheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[sheetName];

        // 将工作表转换为JSON数据
        const rawData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

        // 验证表头
        const headers = rawData[0];
        const expectedHeaders = ['菜品分类', '菜品名称', '单位', '报价'];

        console.log('解析到的表头:', headers);
        console.log('期望的表头:', expectedHeaders);

        if (!this.validateHeaders(headers, expectedHeaders)) {
          this.$message.error('Excel文件格式不正确，请使用正确的模版格式');
          return;
        }

        // 解析上传的数据行
        const uploadedQuotes = new Map(); // 用于存储上传的报价数据
        console.log('原始数据行数:', rawData.length);

        for (let i = 1; i < rawData.length; i++) {
          const row = rawData[i];
          console.log(`第${i + 1}行数据:`, row);

          if (row.length === 0 || row.every(cell => !cell)) {
            console.log(`第${i + 1}行为空行，跳过`);
            continue; // 跳过空行
          }

          const [category, name, unit, price] = row;
          const key = `${category?.trim()}_${name?.trim()}_${unit?.trim()}`;

          if (category && name && unit) {
            uploadedQuotes.set(key, {
              category: category.trim(),
              name: name.trim(),
              unit: unit.trim(),
              quoted_price: price ? parseFloat(price) : null,
              rowNumber: i + 1
            });
          }
        }

        // 以官方参考价格表为主，生成预览数据
        const previewData = [];
        const missingQuotes = []; // 缺失的报价
        const extraQuotes = []; // 多余的报价

        // 遍历官方参考价格表中的每个菜品
        this.dishList.forEach((dish, index) => {
          const key = `${dish.category}_${dish.name}_${dish.unit}`;
          const uploadedQuote = uploadedQuotes.get(key);

          if (uploadedQuote) {
            // 找到匹配的报价
            if (uploadedQuote.quoted_price && uploadedQuote.quoted_price > 0) {
              previewData.push({
                ...dish,
                quoted_price: uploadedQuote.quoted_price,
                status: 'valid',
                rowNumber: uploadedQuote.rowNumber,
                error: null
              });
            } else {
              // 报价为空或无效
              previewData.push({
                ...dish,
                quoted_price: uploadedQuote.quoted_price || '',
                status: 'invalid',
                rowNumber: uploadedQuote.rowNumber,
                error: '报价不能为空且必须大于0'
              });
              missingQuotes.push(dish);
            }
            uploadedQuotes.delete(key); // 从上传数据中移除已匹配的
          } else {
            // 官方参考价格表中有但上传文件中没有
            previewData.push({
              ...dish,
              quoted_price: '',
              status: 'invalid',
              rowNumber: null,
              error: '供应商未提供报价'
            });
            missingQuotes.push(dish);
          }
        });

        // 检查上传文件中多余的报价
        uploadedQuotes.forEach((quote, key) => {
          extraQuotes.push({
            category: quote.category,
            name: quote.name,
            unit: quote.unit,
            quoted_price: quote.quoted_price,
            status: 'invalid',
            rowNumber: quote.rowNumber,
            error: '菜品不在官方参考价格表中',
            isExtra: true
          });
        });

        // 将多余的报价添加到预览数据末尾
        previewData.push(...extraQuotes);

        this.previewData = previewData;
        this.validDataCount = this.previewData.filter(item => item.status === 'valid').length;

        // 显示统计信息
        const totalDishes = this.dishList.length;
        const validQuotes = this.validDataCount;
        const missingCount = missingQuotes.length;
        const extraCount = extraQuotes.length;

        let message = `解析完成：官方参考价格表共${totalDishes}个菜品，`;
        message += `有效报价${validQuotes}个，`;

        if (missingCount > 0) {
          message += `缺失报价${missingCount}个，`;
        }

        if (extraCount > 0) {
          message += `多余菜品${extraCount}个（无法提交），`;
        }

        this.$message.success(message);

        // 自动跳转到预览数据页面
        this.currentStep = 1;

      } catch (error) {
        console.error('解析Excel文件失败:', error);
        this.$message.error('解析Excel文件失败: ' + error.message);
      }
    },

    validateHeaders(headers, expectedHeaders) {
      if (!headers || headers.length < expectedHeaders.length) {
        return false;
      }

      for (let i = 0; i < expectedHeaders.length; i++) {
        if (headers[i] !== expectedHeaders[i]) {
          return false;
        }
      }

      return true;
    },

    parseRow(row, rowNumber) {
      try {
        const [category, name, unit, price] = row;

        // 验证必填字段
        if (!category || !name || !unit || !price) {
          return {
            category: category || '',
            name: name || '',
            unit: unit || '',
            quoted_price: price || 0,
            status: 'invalid',
            error: '必填字段不能为空',
            rowNumber
          };
        }

        // 验证价格格式
        const numPrice = parseFloat(price);
        if (isNaN(numPrice) || numPrice <= 0) {
          return {
            category,
            name,
            unit,
            quoted_price: price,
            status: 'invalid',
            error: '报价必须是大于0的数字',
            rowNumber
          };
        }

        // 验证字符串长度
        if (category.length > 50 || name.length > 100 || unit.length > 20) {
          return {
            category,
            name,
            unit,
            quoted_price: numPrice,
            status: 'invalid',
            error: '字段长度超出限制',
            rowNumber
          };
        }

        // 验证菜品是否在官方参考价格表中
        const trimmedCategory = category.trim();
        const trimmedName = name.trim();
        const trimmedUnit = unit.trim();

        const matchedDish = this.dishList.find(dish =>
          dish.category === trimmedCategory &&
          dish.name === trimmedName &&
          dish.unit === trimmedUnit
        );

        if (!matchedDish) {
          return {
            category: trimmedCategory,
            name: trimmedName,
            unit: trimmedUnit,
            quoted_price: numPrice,
            status: 'invalid',
            error: '菜品不在官方参考价格表中',
            rowNumber
          };
        }

        return {
          category: trimmedCategory,
          name: trimmedName,
          unit: trimmedUnit,
          quoted_price: numPrice,
          dish_id: matchedDish.id, // 保存匹配的菜品ID
          status: 'valid',
          rowNumber
        };

      } catch (error) {
        return {
          category: row[0] || '',
          name: row[1] || '',
          unit: row[2] || '',
          quoted_price: row[3] || 0,
          status: 'invalid',
          error: '数据格式错误',
          rowNumber
        };
      }
    },

    async downloadTemplate() {
      try {
        // 生成报价模板
        const XLSX = await import('xlsx');

        // 创建模版数据
        const templateData = this.dishList.map(dish => ({
          '菜品分类': dish.category,
          '菜品名称': dish.name,
          '单位': dish.unit,
          '报价': ''
        }));

        // 创建工作簿
        const workbook = XLSX.utils.book_new();

        // 创建工作表
        const worksheet = XLSX.utils.json_to_sheet(templateData);

        // 设置列宽
        const colWidths = [
          { wch: 15 }, // 菜品分类
          { wch: 20 }, // 菜品名称
          { wch: 10 }, // 单位
          { wch: 12 }  // 报价
        ];
        worksheet['!cols'] = colWidths;

        // 添加工作表到工作簿
        XLSX.utils.book_append_sheet(workbook, worksheet, '供应商报价模版');

        // 生成Excel文件
        const excelBuffer = XLSX.write(workbook, { type: 'array', bookType: 'xlsx' });

        // 生成文件名
        const fileName = `${this.supplierInfo?.supplier?.name || '供应商'}_报价模版_${new Date().toISOString().slice(0, 10)}.xlsx`;

        // 创建blob并下载
        const blob = new Blob([excelBuffer], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        });

        // 创建下载链接
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = fileName;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);

        this.$message.success('模板下载成功');
      } catch (error) {
        console.error('下载模版失败:', error);
        this.$message.error('模板下载失败: ' + error.message);
      }
    },

    confirmImport() {
      if (!this.supplierInfo || !this.uploadedFile) {
        this.$message.error('数据不完整，无法导入');
        return;
      }

      // 提示确认对话框
      this.$confirm('如果已导入过报价，本次导入会覆盖之前导入的报价数据，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.importData();
      });
    },

    getMissingCount() {
      return this.previewData.filter(item =>
        item.status === 'invalid' &&
        !item.isExtra &&
        item.error === '供应商未提供报价'
      ).length;
    },

    getExtraCount() {
      return this.previewData.filter(item => item.isExtra).length;
    },

    getPreviewTitle() {
      const missingCount = this.getMissingCount();
      const extraCount = this.getExtraCount();

      if (extraCount > 0) {
        return `存在多余菜品，无法提交`;
      } else if (missingCount > 0) {
        return `部分菜品缺失报价`;
      } else if (this.validDataCount === this.dishList.length) {
        return `所有菜品报价完整`;
      } else {
        return `报价数据预览`;
      }
    },

    getPreviewType() {
      const extraCount = this.getExtraCount();
      const missingCount = this.getMissingCount();

      if (extraCount > 0) {
        return 'error';
      } else if (missingCount > 0) {
        return 'warning';
      } else {
        return 'success';
      }
    },

    getConfirmTitle() {
      const extraCount = this.getExtraCount();
      const missingCount = this.getMissingCount();

      if (extraCount > 0) {
        return '存在多余菜品，无法提交';
      } else if (missingCount > 0) {
        return '部分菜品缺失报价，确认导入？';
      } else {
        return '确认导入报价数据';
      }
    },

    getConfirmType() {
      const extraCount = this.getExtraCount();
      const missingCount = this.getMissingCount();

      if (extraCount > 0) {
        return 'error';
      } else if (missingCount > 0) {
        return 'warning';
      } else {
        return 'success';
      }
    },

    importData() {
      // 检查是否有多余的菜品
      const extraCount = this.getExtraCount();
      if (extraCount > 0) {
        this.$message.error(`存在${extraCount}个多余菜品，请修正后重新导入`);
        return;
      }

      const validQuotes = this.previewData.filter(item => item.status === 'valid');
      console.log(validQuotes);
      const importData = {
        monthly_bidding_supplier_id: this.supplierInfo.id,
        monthly_bidding_id: this.biddingInfo.id,
        supplier_id: this.supplierInfo.supplier_id,
        quotes: validQuotes.map(quote => ({
          dish_id: quote.id,
          quoted_price: quote.quoted_price
        }))
      };

      // 调用后端接口批量创建报价
      this.importLoading = true
      http.supplierQuote.batchCreate(importData).then(() => {
        this.$message.success('报价导入成功');
        this.dialogValue = false;
        this.$emit('get-page');
      }).finally(() => {
        this.importLoading = false
      });
    }
  }
};
</script>

<style scoped lang="scss">
.import-quote {
  .supplier-info {
    margin-bottom: 20px;
  }

  .import-steps {
    margin-bottom: 30px;
  }

  .step-content {
    h4 {
      margin-bottom: 20px;
      color: #303133;
    }
  }

  .upload-area {
    margin-bottom: 30px;
  }

  .template-download {
    background: #f5f7fa;
    padding: 20px;
    border-radius: 4px;

    h5 {
      margin-bottom: 10px;
      color: #303133;
    }

    ul {
      margin: 10px 0;
      padding-left: 20px;
    }

    li {
      margin-bottom: 5px;
    }
  }

  .preview-info {
    margin-bottom: 20px;
  }

  .confirm-info {
    margin-bottom: 20px;
  }
}

.dialog-footer {
  text-align: right;
}
</style>
